package com.wyj.controller;


import com.wyj.annotation.LoginRequired;
import com.wyj.pojo.User;
import com.wyj.service.imp.UserServiceImp;
import com.wyj.util.CommunityUtil;
import com.wyj.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/7/8
 */
@Controller
public class UserController {

    @Autowired
    UserServiceImp userServiceImp;

    @Value("${community.path.domain}")
    String contentPath;

    @Value("${community.path.upload}")
    String uploadPath;

    //我们在拦截器那里将 登录的一个用户的信息获取到
    @Autowired
    HostHolder hostHolder;

    @LoginRequired
    @GetMapping(path = "/set")
    public String getSetPage() {
        return "/site/setting";
    }

    @LoginRequired
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String updateHeaderUrl(MultipartFile headerImage, Model model) {

        //处理上传图片为空的状态
        if (headerImage == null) {
            model.addAttribute("errorMsg", "您上传的图片不能为空");
            return "/site/setting";
        }

        //获取到上传图片的名称
        String filename = headerImage.getOriginalFilename();
        //截取上传图片的后缀
        String stuff = filename.substring(filename.lastIndexOf("."));

        if (StringUtils.isBlank(stuff)) {
            model.addAttribute("errorMsg", "您上传的图片格式有问题");
        }

        filename = CommunityUtil.getUUID() + stuff;

        //服务器中产生保存 上传图片 的路径 (目前还未存放文件)
        File file = new File(uploadPath + "/" + filename);

        //将 上传的文件存放下来
        try {
            headerImage.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败  服务器异常", e);
        }

        User user = hostHolder.getUser();
        String headerUrl = contentPath + "/user/header/" + filename;

        int i = userServiceImp.updateUserHeaderUrl(user.getId(), headerUrl);

        return "redirect:/index";
    }

    /**
     * @Description 上方的Controller已经将文件 存在指定的位置啦
     * 那么这个请求是将我们存的文件 变成流输出  但是这个是将流放在 响应体当中
     * @retuen 返回值说明
     * @author 创建人
     * @since 创建日期
     */

    //index.html中 那个头像取值(loginUser.headerUrl)的时候的 需要我们完成这个请求
    @RequestMapping(value = "/user/header/{filename}", method = RequestMethod.POST)
    @ResponseBody
    public void getUserHeaderUrl(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {


        System.out.println("====================");

        //存取文件的路径
        filename = uploadPath + "/" + filename;


        String stuff = filename.substring(filename.lastIndexOf(".")+1);

        //设置响应体的类型
        response.setContentType("image/" + stuff);

        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(filename);

            outputStream = response.getOutputStream();

            byte[] bytes = new byte[1024];
            int b = 0;
            //将 inputStream.read(bytes) 赋值给 b
            while ((b = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, b);
            }
        } catch (IOException e) {
            System.out.println("==============读取头像失败=============");
            e.printStackTrace();
        } finally {

        }


    }


}
